<?php

class ProjectController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->stylesBase = $this->view->baseUrl() . '/styles/';
    }
    
    public function preDispatch()
    {
        if(isset(Zend_Auth::getInstance()->getStorage()->read()->user_role))
        {
            $role = Zend_Auth::getInstance()->getStorage()->read()->user_role;
        
        }
        
        if(zend_auth::getInstance()->hasIdentity()){
            switch ($this->getRequest()->getActionName()) {
                case 'add':
                    if($role != 'projectmanager')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'list':
                    if($role != 'projectmanager')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'details':
                    if($role != 'projectmanager')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'deleteuserfromproject':
                    break;
                case 'deleteproject':
                    break;
                default:
                        $this->_helper->redirector('index', 'index');
                    break;
            }
        }
        else {
            // niet ingelogd
            switch ( $this->getRequest()->getActionName() ) {
                default: $this->_helper->redirector('index');
                    break;
            }
        }
            
        
    }

    public function indexAction()
    {
        $view = $this->_getView('projecten');
    }

    public function addAction()
    {
        $view = $this->_getView('project toevoegen');
        $form = new Application_Form_Project();
        $storage = Zend_Auth::getInstance()->getStorage()->read();
        $request = $this->getRequest();
        
        if($request->isPost()){
            if($form->isValid($request->getPost()) )
            {
                $project = new Application_Model_Project($form->getValues());
                $project->Creator = $storage->user_id;
                $startdate = $form->getValue('starttime');
                $enddate = $form->getValue('endtime');
                $timestampstart = strtotime($startdate,time());
                $timestampend = strtotime($enddate,time());
                $startdate = date('Y-m-d',$timestampstart);
                $endate = date('Y-m-d',$timestampend);
                $project->Endtime = $endate;
                $project->Starttime = $startdate;
                $projectmapper = new Application_Model_Projectmapper();
                $projectmapper->save($project);
                
                $this->_helper->redirector('list', 'project');
                
            }
        }
        $view->form = $form;
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
    }

    private function _getView($title)
    {
        
        $view = $this->view; // view instellen
        $view->title = $title; // titel instellen op meegegeven waarde
        $view->headTitle($view->title, 'prepend'); // titel van pagina instellen
        $view->headLink()->appendStylesheet($this->stylesBase . 'main.css'); // stylesheets koppelen in de head

        return $view; // return het viewobject
    }

    public function listAction()
    {
        $view = $this->_getView('Projects');
        
        $projectmapper = new Application_Model_Projectmapper();
        $storage = Zend_auth::getInstance()->getStorage()->read();
        $creatorid = $storage->user_id;
        
        $projecten = $projectmapper->fetchByCreatorId($creatorid);
        
        
        
        $view->entries = $projecten;
        
    }

    public function detailsAction()
    {
        
        
        $auth = Zend_Auth::getInstance()->getIdentity();
        $projectmapper = new Application_Model_Projectmapper();
        $projectid = $this->getRequest()->getParam('projectid');
        $view = $this->_getView('Projectdetails');
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        $projectdetailsform = new Application_Form_Projectdetails();
        $storage = Zend_Auth::getInstance()->getStorage()->read();
        $request = $this->getRequest();
        $addusertoprojectform = new Application_Form_Addusertoproject();
        
        
        
        if(!$this->_checkIfUserIsPermitted($projectid, true))
        {
            $this->_helper->redirector('list', 'project');
        }
        
        $project = $projectmapper->fetchById($projectid);
        $populatearray = array('id'=>$project->Id, 'name'=>$project->Name,'description'=>$project->getDescription(),'starttime'=>$project->Starttime,'endtime'=>$project->Endtime);
        $projectdetailsform->populate($populatearray);
        
        
        if($request->isPost())
        {
            
            if($request->getPost('toevoegen') && $request->getPost('email'))
            {
                if($addusertoprojectform->isValid($request->getPost()))
                {
                    $email = $addusertoprojectform->getValue('email');

                    if(!$this->_addusertoproject($email,$projectid)){
                        $addusertoprojectform->getElement('email')->setErrors(array('user does not exist or has already been added' =>'user does not exist or has already been added'));

                    }
                    else
                    {
                        $addusertoprojectform->getElement('email')->setValue('');
                    }
                }
            }
            if($request->getPost('submit'))
            {
                if($projectdetailsform->isValid($request->getPost()))
                {
                    $project = new Application_Model_Project($projectdetailsform->getValues());
                    $project->Creator = $storage->user_id;
                    $projectmapper->save($project);
                }
                
            }
        }
        $view->projectdetailsform = $projectdetailsform;
        $view->addusertoprojectform = $addusertoprojectform;
        
        
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        
        
        $usermapper = new Application_Model_UserMapper();
        
        
        $users = $usermapper->fetchByProjectId($projectid);
        
        $view->users = $users;
        $view->projectid = $projectid;
        
    }

    public function deleteuserfromprojectAction()
    {
        
        
        $this->_helper->layout()->disableLayout();       // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);
        
        $request = $this->getRequest();
        
        // variabelen uit request halen, deze zijn verplicht
        $userid = $request->getParam('userid');
        $projectid = $request->getParam('projectid');
        
        
        if($userid !== null && $projectid !== null && $this->_checkIfUserIsPermitted($projectid, false) )
        {
            $usermapper = new Application_Model_UserMapper();
            if($usermapper->deleteUserFromProject($userid, $projectid))
            {
                echo 'User deleted';
            }
            else
            {
                echo 'User was already deleted';
            }
            
             
        }
        else
        {
            echo 'You are not authorised';
        }
        
    }
    
    public function deleteprojectAction()
    {
        $this->_helper->layout()->disableLayout();       // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);
        
        $request = $this->getRequest();
        
        // variabelen uit request halen, deze zijn verplich
        $projectid = $request->getParam('projectid');
        
        if($projectid !== null && $this->_checkIfUserIsPermitted($projectid,false))
        {
            $projectmapper = new Application_Model_Projectmapper();
            if($projectmapper->delete($projectid))
            {
                echo 'Project deleted';
            }
            else
            {
                echo 'Project was already deleted';
            }
        }
        else
        {
            echo 'You are not authorised';
        }
    }

    protected function _addusertoproject($usermail, $projectid)
    {
        
        
        
        if($usermail !== null && $projectid !== null)
        {
            $usermapper = new Application_Model_UserMapper();
            $user = $usermapper->fechByEmail($usermail);
            
            if($user)
            {
                
                
                if($usermapper->addUserToProject($user->Id, $projectid))
                {
                    return true;
                    
                }
                
            }
            
        }
        
        return false;
    }

    protected function _checkIfUserIsPermitted($projectid, $adminpermitted = true)
    {
        // identiteit opvragen
        $auth = Zend_Auth::getInstance()->getIdentity();
        $projectmapper = new Application_Model_Projectmapper();
        
        
        
        // er is iemand ingelogd
        if($auth != null)
        {
            $userid = $auth->user_id;

            $userrole = $auth->user_role;
            
            // de gebruiker is ingelogd als projectmanager
            if ($userrole === 'projectmanager')
            {
                if($projectmapper->doesUserOwnsProject($userid, $projectid))
                {
                    //de gebruiker is eigenaar van het project
                    
                    return true;
                }
            }
            // de gebruiker is admin
            elseif($userrole ==='admin')
            {
                
                if($adminpermitted === true)
                {
                    return true;
                }
            }
            else
            {
                return false; 
            }
            
           
                
        }
        
        return false;
        
    }

    


}













